import axios from "axios";
import {getToken, removeToken} from "./local";
import {message} from "antd";
import history from "./history";
import {useState} from "react";


export const baseURL = 'http://geek.itheima.net/v1_0'

// 基准地址
const server = axios.create({
  baseURL,
})

//请求拦截器
server.interceptors.request.use(config => {
  // 添加token
  const token = getToken()
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 相应拦截器
server.interceptors.response.use(
  response => {

    // 200-300
    return response.data
  },
  error => {
    // token过期了 状态吗 401
    if (error.response.status === 401) {
      //  没有权限
      removeToken()
      message.warning('用户信息过期')
      //  跳转登录界面
      history.push('/login')
    }
    return Promise.reject(error)
  }
)


// 默认导出
export default server;
